<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="在工业控制、电力通讯、智能仪表等领域，通常情况下是采用串口通信的方式进行数据交换。最初采用的方式是 RS232 接口，由于工业现场比较复杂，各种电气设备会在环境中产生比较多的电磁干扰，会导致信号传输错误。除此之外，RS232 接口只能实现点对点通信，不具备联网功能，最大传输距离也只能达到十几米，不能满足远距离通信要求。而 RS485 则解决了这些问题，数据信号采用差分传输方式，可以有效的解决共模干">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="18.1、RS485通信">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu117/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="在工业控制、电力通讯、智能仪表等领域，通常情况下是采用串口通信的方式进行数据交换。最初采用的方式是 RS232 接口，由于工业现场比较复杂，各种电气设备会在环境中产生比较多的电磁干扰，会导致信号传输错误。除此之外，RS232 接口只能实现点对点通信，不具备联网功能，最大传输距离也只能达到十几米，不能满足远距离通信要求。而 RS485 则解决了这些问题，数据信号采用差分传输方式，可以有效的解决共模干">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250H52MD.png">
<meta property="og:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250HAW22.png">
<meta property="og:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250I9221A.png">
<meta property="og:updated_time" content="2019-01-31T13:14:53.373Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="18.1、RS485通信">
<meta name="twitter:description" content="在工业控制、电力通讯、智能仪表等领域，通常情况下是采用串口通信的方式进行数据交换。最初采用的方式是 RS232 接口，由于工业现场比较复杂，各种电气设备会在环境中产生比较多的电磁干扰，会导致信号传输错误。除此之外，RS232 接口只能实现点对点通信，不具备联网功能，最大传输距离也只能达到十几米，不能满足远距离通信要求。而 RS485 则解决了这些问题，数据信号采用差分传输方式，可以有效的解决共模干">
<meta name="twitter:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250H52MD.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu117/">





  <title>18.1、RS485通信 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu117/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">18.1、RS485通信</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:41:17+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在工业控制、电力通讯、智能仪表等领域，通常情况下是采用串口通信的方式进行数据交换。最初采用的方式是 RS232 接口，由于工业现场比较复杂，各种电气设备会在环境中产生比较多的电磁干扰，会导致信号传输错误。除此之外，RS232 接口只能实现点对点通信，不具备联网功能，最大传输距离也只能达到十几米，不能满足远距离通信要求。而 RS485 则解决了这些问题，数据信号采用差分传输方式，可以有效的解决共模干扰问题，最大距离可达 1200 米，并且允许多个收发设备接到同一条总线上。随着工业应用通信越来越多，1979年施耐德电气制定了一个用于工业现场的总线协议 Modbus 协议，现在工业中使用 RS485 通信场合很多都采用 Modbus 协议，本节课我们就来讲解一下 RS485 通信和 Modbus 协议。</p>
<p>单单使用一块 KST-51 开发板是不能够进行 RS485 实验的，应很多同学的要求，把这节课作为扩展课程讲一下，如果要做本课相关实验，需要自行购买 USB 转 RS485 通信模块，或连接其它的 RS485 主控设备进行。</p>
<hr>
<p>RS232 标准是诞生于 RS485 之前的，但是 RS232 有几处不足的地方：</p>
<ol>
<li>接口的信号电平值较高，达到十几 V，使用不当容易损坏接口芯片，电平标准也与TTL 电平不兼容。</li>
<li>传输速率有局限，不可以过高，一般到一两百千比特每秒(Kb/s)就到极限了。</li>
<li>接口使用信号线和 GND 与其它设备形成共地模式的通信，这种共地模式传输容易产生干扰，并且抗干扰性能也比较弱。</li>
<li>传输距离有限，最多只能通信几十米。</li>
<li>通信的时候只能两点之间进行通信，不能够实现多机联网通信。</li>
</ol>
<p>针对 RS232 接口的不足，就不断出现了一些新的接口标准，RS485 就是其中之一，它具备以下的特点：</p>
<ol>
<li>采用差分信号。我们在讲 A/D 的时候，讲过差分信号输入的概念，同时也介绍了差分输入的好处，最大的优势是可以抑制共模干扰。尤其当工业现场环境比较复杂，干扰比较多时，采用差分方式可以有效的提高通信可靠性。RS485 采用两根通信线，通常用 A 和 B 或者 D+和 D-来表示。逻辑“1”以两线之间的电压差为+(0.2~6)V 表示，逻辑“0”以两线间的电压差为-(0.2~6)V 来表示，是一种典型的差分通信。</li>
<li>RS485 通信速率快，最大传输速度可以达到 10Mb/s 以上。</li>
<li>RS485 内部的物理结构，采用的是平衡驱动器和差分接收器的组合，抗干扰能力也大大增加。</li>
<li>传输距离最远可以达到 1200 米左右，但是它的传输速率和传输距离是成反比的，只有在 100Kb/s 以下的传输速度，才能达到最大的通信距离，如果需要传输更远距离可以使用中继。</li>
<li>可以在总线上进行联网实现多机通信，总线上允许挂多个收发器，从现有的 RS485芯片来看，有可以挂 32、64、128、256 等不同个设备的驱动器。</li>
<li>RS485 的接口非常简单，与 RS232 所使用的 MAX232 是类似的，只需要一个 RS485转换器，就可以直接与单片机的 UART 串口连接起来，并且使用完全相同的异步串行通信协议。但是由于 RS485 是差分通信，因此接收数据和发送数据是不能同时进行的，也就是说它是一种半双工通信。那我们如何判断什么时候发送，什么时候接收呢？</li>
</ol>
<p>RS485 转换芯片很多，这节课我们以典型的 MAX485 为例讲解 RS485 通信，如图 18-1所示。</p>
<p><img src="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250H52MD.png" alt></p>
<center><strong>图 18-1  MAX485 硬件接口</strong></center>

<p>MAX485 是美信(Maxim)推出的一款常用 RS485 转换器。其中 5 脚和 8 脚是电源引脚；6脚和 7 脚就是 RS485 通信中的 A 和 B 两个引脚；1 脚和 4 脚分别接到单片机的 RXD 和 TXD引脚上，直接使用单片机 UART 进行数据接收和发送；2 脚和 3 脚是方向引脚，其中 2 脚是低电平使能接收器，3 脚是高电平使能输出驱动器，我们把这两个引脚连到一起，平时不发送数据的时候，保持这两个引脚是低电平，让 MAX485 处于接收状态，当需要发送数据的时候，把这个引脚拉高，发送数据，发送完毕后再拉低这个引脚就可以了。为了提高 RS485 的抗干扰能力，需要在靠近 MAX485 的 A 和 B 引脚之间并接一个电阻，这个电阻阻值从 100欧到 1K 都是可以。</p>
<p>在这里我们还要介绍一下如何使用 KST-51 单片机开发板进行外围扩展实验。我们的开发板只能把基本的功能给同学们做出来提供实验练习，但是同学们学习的脚步不应该停留在这个实验板上。如果想进行更多的实验，就可以通过单片机开发板的扩展接口进行扩展实验。大家可以看到蓝绿色的单片机座周围有 32 个插针，这 32 个插针就是把单片机的 32 个 IO 引脚全部都引出来了。在原理图上体现出来的就是 J4、J5、J6、J7 这 4 个器件，如图 18-2 所示。</p>
<p><img src="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250HAW22.png" alt></p>
<center><strong>图 18-2  单片机扩展接口</strong></center>

<p>这 32 个 IO 口中并不是所有的都可以用来对外扩展，其中既作为数据输出，又可以作为数据输入的引脚是不可以用的，比如 P3.2、P3.4、P3.6 引脚，这三个引脚是不可用的。比如P3.2 这个引脚，如果我们用来扩展，发送的信号如果和 DS18B20 的时序吻合，会导致 DS18B20拉低引脚，影响通信。除这 3 个 IO 口以外的其它 29 个，都可以使用杜邦线接上插针，扩展出来使用。当然了，如果把当前的 IO 口应用于扩展功能了，板子上的相应功能就实现不了了，也就是说需要扩展功能和板载功能之间二选一。</p>
<p>在进行 RS485 实验中，我们通信用的引脚必须是 P3.0 和 P3.1，此外还有一个方向控制引脚，我们使用杜邦线将其连接到 P1.7 上去。RS485 的另外一端，大家可以使用一个 USB转 RS485 模块，用双绞线把开发板和模块上的 A 和 B 分别对应连起来，USB 那头插入电脑，然后就可以进行通信了。</p>
<p>学习了第 13 章实用的串口通信方法和程序后，做这种串口通信的方法就很简单了，基本是一致的。我们使用实用串口通信例程的思路，做了一个简单的程序，通过串口调试助手下发任意个字符，单片机接收到后在末尾添加“回车+换行”符后再送回，在调试助手上重新显示出来，先把程序贴出来。</p>
<p>程序中需要注意的一点是：因为平常都是将 MAX485 设置为接收状态，只有在发送数据的时候才将 MAX485 改为发送状态，所以在 UartWrite()函数开头将 MAX485 方向引脚拉高，函数退出前再拉低。但是这里有一个细节，就是单片机的发送和接收中断产生的时刻都是在停止位的一半上，也就是说每当停止位传送了一半的时候，RI 或 TI 就已经置位并且马上进入中断（如果中断使能的话）函数了，接收的时候自然不会存在问题，但发送的时候就不一样了：当紧接着向 SBUF 写入一个字节数据时，UART 硬件会在完成上一个停止位的发送后，再开始新字节的发送，但如果此时不是继续发送下一个字节，而是已经发送完毕了，要停止发送并将 MAX485 方向引脚拉低以使 MAX485 重新处于接收状态时就有问题了，因为这时候最后的这个停止位实际只发送了一半，还没有完全完成，所以就有了 UartWrite()函数内DelayX10us(5)这个操作，这是人为的增加了 50us 的延时，这 50us 的时间正好让剩下的一半停止位完成，那么这个时间自然就是由通信波特率决定的了，为波特率周期的一半。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line">/****************************RS485.c 文件程序源代码*****************************/</span><br><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">#include &lt;intrins.h&gt;</span><br><span class="line">sbit RS485_DIR = P1^7; //RS485 方向选择引脚</span><br><span class="line">bit flagFrame = 0; //帧接收完成标志，即接收到一帧新数据</span><br><span class="line">bit flagTxd = 0; //单字节发送完成标志，用来替代 TXD 中断标志位</span><br><span class="line">unsigned char cntRxd = 0; //接收字节计数器</span><br><span class="line">unsigned char pdata bufRxd[64]; //接收字节缓冲区</span><br><span class="line">extern void UartAction(unsigned char *buf, unsigned char len);</span><br><span class="line">/* 串口配置函数，baud-通信波特率 */</span><br><span class="line">void ConfigUART(unsigned int baud)&#123;</span><br><span class="line">    RS485_DIR = 0; //RS485 设置为接收方向</span><br><span class="line">    SCON = 0x50; //配置串口为模式 1</span><br><span class="line">    TMOD &amp;= 0x0F; //清零 T1 的控制位</span><br><span class="line">    TMOD |= 0x20; //配置 T1 为模式 2</span><br><span class="line">    TH1 = 256 - (11059200/12/32)/baud; //计算 T1 重载值</span><br><span class="line">    TL1 = TH1; //初值等于重载值</span><br><span class="line">    ET1 = 0; //禁止 T1 中断</span><br><span class="line">    ES = 1; //使能串口中断</span><br><span class="line">    TR1 = 1; //启动 T1</span><br><span class="line">&#125;</span><br><span class="line">/* 软件延时函数，延时时间(t*10)us */</span><br><span class="line">void DelayX10us(unsigned char t)&#123;</span><br><span class="line">    do &#123;</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">        _nop_();</span><br><span class="line">    &#125; while (--t);</span><br><span class="line">&#125;</span><br><span class="line">/* 串口数据写入，即串口发送函数，buf-待发送数据的指针，len-指定的发送长度 */</span><br><span class="line">void UartWrite(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    RS485_DIR = 1; //RS485 设置为发送</span><br><span class="line">   </span><br><span class="line">    while (len--)&#123; //循环发送所有字节</span><br><span class="line">        flagTxd = 0; //清零发送标志</span><br><span class="line">        SBUF = *buf++; //发送一个字节数据</span><br><span class="line">        while (!flagTxd); //等待该字节发送完成</span><br><span class="line">    &#125;</span><br><span class="line">    DelayX10us(5); //等待最后的停止位完成，延时时间由波特率决定</span><br><span class="line">    RS485_DIR = 0; //RS485 设置为接收</span><br><span class="line">&#125;</span><br><span class="line">/* 串口数据读取函数，buf-接收指针，len-指定的读取长度，返回值-实际读到的长度 */</span><br><span class="line">unsigned char UartRead(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    unsigned char i;</span><br><span class="line">    //指定读取长度大于实际接收到的数据长度时，</span><br><span class="line">    //读取长度设置为实际接收到的数据长度</span><br><span class="line">    if (len &gt; cntRxd)&#123;</span><br><span class="line">        len = cntRxd;</span><br><span class="line">    &#125;</span><br><span class="line">    for (i=0; i&lt;len; i++)&#123; //拷贝接收到的数据到接收指针上</span><br><span class="line">        *buf++ = bufRxd[i];</span><br><span class="line">    &#125;</span><br><span class="line">    cntRxd = 0; //接收计数器清零</span><br><span class="line">    return len; //返回实际读取长度</span><br><span class="line">&#125;</span><br><span class="line">/* 串口接收监控，由空闲时间判定帧结束，需在定时中断中调用，ms-定时间隔 */</span><br><span class="line">void UartRxMonitor(unsigned char ms)&#123;</span><br><span class="line">    static unsigned char cntbkp = 0;</span><br><span class="line">    static unsigned char idletmr = 0;</span><br><span class="line">   </span><br><span class="line">    if (cntRxd &gt; 0)&#123; //接收计数器大于零时，监控总线空闲时间</span><br><span class="line">        if (cntbkp != cntRxd)&#123; //接收计数器改变，即刚接收到数据时，清零空闲计时</span><br><span class="line">            cntbkp = cntRxd;</span><br><span class="line">            idletmr = 0;</span><br><span class="line">        &#125;else&#123; //接收计数器未改变，即总线空闲时，累积空闲时间</span><br><span class="line">            if (idletmr &lt; 30)&#123; //空闲计时小于 30ms 时，持续累加</span><br><span class="line">                idletmr += ms;</span><br><span class="line">                if (idletmr &gt;= 30)&#123; //空闲时间达到 30ms 时，即判定为一帧接收完毕</span><br><span class="line">                    flagFrame = 1; //设置帧接收完成标志</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        cntbkp = 0;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口驱动函数，监测数据帧的接收，调度功能函数，需在主循环中调用 */</span><br><span class="line">void UartDriver()&#123;</span><br><span class="line">    unsigned char len;</span><br><span class="line">    unsigned char pdata buf[40];</span><br><span class="line">   </span><br><span class="line">    if (flagFrame)&#123; //有命令到达时，读取处理该命令</span><br><span class="line">        flagFrame = 0;</span><br><span class="line">        len = UartRead(buf, sizeof(buf)-2); //将接收到的命令读取到缓冲区中</span><br><span class="line">        UartAction(buf, len); //传递数据帧，调用动作执行函数</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口中断服务函数 */</span><br><span class="line">void InterruptUART() interrupt 4&#123;</span><br><span class="line">    if (RI)&#123; //接收到新字节</span><br><span class="line">        RI = 0; //清零接收中断标志位</span><br><span class="line">        //接收缓冲区尚未用完时，保存接收字节，并递增计数器</span><br><span class="line">        if (cntRxd &lt; sizeof(bufRxd))&#123;</span><br><span class="line">            bufRxd[cntRxd++] = SBUF;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    if (TI)&#123; //字节发送完毕</span><br><span class="line">        TI = 0; //清零发送中断标志位</span><br><span class="line">        flagTxd = 1; //设置字节发送完成标志</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>/<strong><strong><strong><strong><strong><strong><strong>*</strong></strong></strong></strong></strong></strong></strong>main.c 文件程序源代码<strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong>/</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">unsigned char T0RH = 0; //T0 重载值的高字节</span><br><span class="line">unsigned char T0RL = 0; //T0 重载值的低字节</span><br><span class="line">void ConfigTimer0(unsigned int ms);</span><br><span class="line">extern void UartDriver();</span><br><span class="line">extern void ConfigUART(unsigned int baud);</span><br><span class="line">extern void UartRxMonitor(unsigned char ms);</span><br><span class="line">extern void UartWrite(unsigned char *buf, unsigned char len);</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1; //开总中断</span><br><span class="line">    ConfigTimer0(1); //配置 T0 定时 1ms</span><br><span class="line">    ConfigUART(9600); //配置波特率为 9600</span><br><span class="line">    while (1)&#123;</span><br><span class="line">        UartDriver(); //调用串口驱动</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口动作函数，根据接收到的命令帧执行响应的动作</span><br><span class="line">buf-接收到的命令帧指针，len-命令帧长度 */</span><br><span class="line">void UartAction(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    //在接收到的数据帧后添加换车换行符后发回</span><br><span class="line">    buf[len++] = &apos;\r&apos;;</span><br><span class="line">    buf[len++] = &apos;\n&apos;;</span><br><span class="line">    UartWrite(buf, len);</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 T0，ms-T0 定时时间 */</span><br><span class="line">void ConfigTimer0(unsigned int ms)&#123;</span><br><span class="line">    unsigned long tmp; //临时变量</span><br><span class="line">    tmp = 11059200 / 12; //定时器计数频率</span><br><span class="line">    tmp = (tmp * ms) / 1000; //计算所需的计数值</span><br><span class="line">    tmp = 65536 - tmp; //计算定时器重载值</span><br><span class="line">    tmp = tmp + 33; //补偿中断响应延时造成的误差</span><br><span class="line">    T0RH = (unsigned char)(tmp&gt;&gt;8); //定时器重载值拆分为高低字节</span><br><span class="line">    T0RL = (unsigned char)tmp;</span><br><span class="line">    TMOD &amp;= 0xF0; //清零 T0 的控制位</span><br><span class="line">    TMOD |= 0x01; //配置 T0 为模式 1</span><br><span class="line">    TH0 = T0RH; //加载 T0 重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，执行串口接收监控 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    TH0 = T0RH; //重新加载重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    UartRxMonitor(1); //串口接收监控</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在看这种串口程序，是不是感觉很简单了呢？串口通信程序我们反反复复的使用，加上随着学习的模块越来越多，实践的越来越多，原先感觉很复杂的东西，现在就会感到简单了。从设备管理器里可以查看所有的 COM 口号，我们下载程序用的是 COM4，而 USB 转RS485 虚拟的是 COM5，通信的时候我们用的是 COM5 口，如图 18-3 所示。</p>
<p><img src="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250I9221A.png" alt></p>
<center><strong>图 18-3  RS485 通信试验设置和结果</strong></center>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu116/" rel="next" title="17.7、单片机信号发生器程序">
                <i class="fa fa-chevron-left"></i> 17.7、单片机信号发生器程序
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu118/" rel="prev" title="18.2、Modbus通信协议介绍">
                18.2、Modbus通信协议介绍 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
